package com.wenjh.jdmzt.android.view;

import java.util.Arrays;
import java.util.List;

import android.content.Context;
import android.content.res.Resources;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.wenjh.jdmzt.AndroidKit;
import com.wenjh.jdmzt.android.adapter.BaseListAdapter;
import com.wenjh.jdmzt.R;

public class MAlertListDialog extends MAlertDialog implements OnItemClickListener {
	
	private ListView listView = null;
	private OnItemSelectedListener onItemSelectedListener = null;

	public MAlertListDialog(Context paramContext) {
		super(paramContext);
		setTitleDividerShown(false);
		View view = AndroidKit.getLayoutInflater().inflate(R.layout.include_dialog_simplelist, null);
		setContentView(view);
		
		listView = (ListView) view.findViewById(R.id.listview);
		listView.setOnItemClickListener(this);     
	}
	
	public MAlertListDialog(Context paramContext, CharSequence[] items) {
		this(paramContext);
		setAdatper(new MAdapter(getContext(), Arrays.asList(items)));
	}
	
	public MAlertListDialog(Context paramContext, int arrayId){
		this(paramContext);
		Resources res = paramContext.getResources();
		CharSequence[] planets = res.getStringArray(arrayId);
		setAdatper(new MAdapter(getContext(), Arrays.asList(planets)));
	}
	
	public void setAdatper(ListAdapter adapter) {
		listView.setAdapter(adapter);
	}
	
	private class MAdapter extends BaseListAdapter<CharSequence> {
		public MAdapter(Context context, List<CharSequence> items) {
			super(context, items);
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if(convertView == null) {
				convertView = inflater.inflate(R.layout.listitem_dialog, null);
			}
			
			TextView textView = (TextView) convertView.findViewById(R.id.textview);
			textView.setText(getItem(position));
			
			return convertView;
		}
		
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if(onItemSelectedListener != null) {
			onItemSelectedListener.onItemSelected(position);
		}
		dismiss();
	}
	
	public void setOnItemSelectedListener(
			OnItemSelectedListener onItemSelectedListener) {
		this.onItemSelectedListener = onItemSelectedListener;
	}
}
